
import sys
import os
import urllib
import re
from utilities import *
from song import *
import lyrics

if ( __name__ != "__main__" ):
    import xbmc

__title__ = "Shironet.co.il"
__allow_exceptions__ = True

_ = sys.modules[ "__main__" ].__language__


class XmlUtils :
    def getText (self, nodeParent, childName ):
        # Get child node...
        node = nodeParent.getElementsByTagName( childName )[0]
        
        if node == None :
            return None
        
        # Get child text...
        text = ""
        for child in node.childNodes:
            if child.nodeType == child.TEXT_NODE :
                text = text + child.data
        return text
    
    @staticmethod
    def removeComments(text):
        begin = text.split("<!--")
        if ( len(begin) > 1 ):
            end = str.join("", begin[1:]).split("-->")
            if ( len(end) > 1 ):
                return XmlUtils.removeComments(begin[0] + str.join("", end[1:]))
        return text


class LyricsFetcher:
    """ required: Fetcher Class for www.Shiron.net """
    def __init__( self ):
        self._set_exceptions()
        
        
    def get_lyrics_start(self, *args):
        lyricThread = threading.Thread(target=self.get_lyrics_thread, args=args)
        lyricThread.setDaemon(True)
        lyricThread.start()
    
    
    def get_lyrics_thread(self, song):
        print "SCRAPER-DEBUG: LyricsFetcher.get_lyrics_thread %s" % (song)
        l = lyrics.Lyrics()
        l.song = song
        try:
            url = "http://www.shiron.net/searchSongs?type=lyrics&q=" + urllib.quote(song.artist + " " + song.title)
            print "Search url: %s" % (url)
            lyrics_urls = re.compile('<a href="(/artist\?type=lyrics&lang=1&prfid=\d+&wrkid=\d+)" class="search_link_name_big">').findall(urllib.urlopen(url).read())
            
            if (len(lyrics_urls)==0):
              return None, _(1) % (song.title, song.artist) 
            
            print("lyrics_urls[0]="+lyrics_urls[0])
            
            lyricsPage = urllib.urlopen('http://www.shiron.net'+lyrics_urls[0]).read()
            lyricText = re.findall('<span class="artist_lyrics_text">(.*?)</span>',lyricsPage,re.DOTALL)[0].replace('<br>','')
            
            if ( not lyricText ):
                return None, _(1) % (song.title, song.artist)
            
            l.lyrics = lyricText
            l.source = re.findall("<title>(.*?)</title>",lyricsPage)[0]
            
            return l, None            
        except:
            print "%s::%s (%d) [%s]" % ( self.__class__.__name__, sys.exc_info()[ 2 ].tb_frame.f_code.co_name, sys.exc_info()[ 2 ].tb_lineno, sys.exc_info()[ 1 ])
            return None, _(2) % (__title__)      

    def get_lyrics( self, artist, song ):
        print "SCRAPER-DEBUG: LyricsFetcher.get_lyrics0 ; artist=%s,song=%s" % (artist,song)
        """ *required: Returns song lyrics or a list of choices from artist & song """
        # format artist and song, check for exceptions
        artist = self._format_param( artist )
        song = self._format_param( song, False )
        # fetch lyrics
        lyrics = self._fetch_lyrics( artist, song )
        print "SCRAPER-DEBUG: LyricsFetcher.get_lyrics1 ; artist=%s,song=%s" % (artist,song)
        # if no lyrics found try just artist for a list of songs
        return lyrics
    
    def get_lyrics_from_list( self, item ):
        """ *required: Returns song lyrics from user selection - item[1]"""
        print "SCRAPER-DEBUG: LyricsFetcher.get_lyrics_from_list %s" % (item)
        lyrics = self.get_lyrics( item[ 0 ], item[ 1 ] )
        return lyrics
        
    def _set_exceptions( self, exception=None ):
        """ Sets exceptions for formatting artist """
        try:
            if ( __name__ == "__main__" ):
                ex_path = os.path.join( os.getcwd(), "exceptions.txt" )
            else:
                name = __name__.replace( "resources.scrapers.", "" ).replace( ".lyricsScraper", "" )
                ex_path = os.path.join( xbmc.translatePath( "P:\\script_data" ), os.getcwd(), "scrapers", name, "exceptions.txt" )
            ex_file = open( ex_path, "r" )
            self.exceptions = eval( ex_file.read() )
            ex_file.close()
        except:
            self.exceptions = {}
        if ( exception is not None ):
            self.exceptions[ exception[ 0 ] ] = exception[ 1 ]
            self._save_exception_file( ex_path, self.exceptions )
    
    def _save_exception_file( self, ex_path, exceptions ):
        """ Saves the exception file as a repr(dict) """
        try:
            if ( not os.path.isdir( os.path.split( ex_path )[ 0 ] ) ):
                os.makedirs( os.path.split( ex_path )[ 0 ] )
            ex_file = open( ex_path, "w" )
            ex_file.write( repr( exceptions ) )
            ex_file.close()
        except: pass
        
    def _fetch_lyrics( self, artist, song ):
        """ Fetch lyrics if available """
        print "TODO:Run only from 'get_lyrics_from_list'"
        print "SCRAPER-DEBUG: LyricsFetcher._fetch_lyrics %s,%s" % (artist,song)
        return None
        
    
    def _format_param( self, param, exception=True ):
        """ Converts param to the form expected by www.lyricwiki.org """
        # properly quote string for url
        result = urllib.quote( param )
        # replace any exceptions
        if ( exception and result in self.exceptions ):
            result = self.exceptions[ result ]
        return result
    
# used for testing only
debug = False
debugWrite = False
